package com.jg.servlet;

import com.jg.entity.User;
import com.jg.service.UserService;
import com.jg.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author 86130
 * @version 1.0
 * @description: TODO
 * @date 2025/3/24 11:53
 */
@WebServlet("/login.action")
public class LoginServlet extends HttpServlet {
    UserService userService = new UserServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/json;charset=utf-8");
        resp.setCharacterEncoding("utf-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        User user = userService.login(username, password);
        if (user!=null){
            // 登录成功，设置session
            HttpSession session = req.getSession();

            // 获取上次登录时间（从当前session中获取）
            Object lastLoginObj = session.getAttribute("lastLoginTime");
            String lastLoginTime = lastLoginObj != null ? lastLoginObj.toString() : "首次登录";

            // 存储当前登录时间到session
            session.setAttribute("lastLoginTime", new java.util.Date().toString());
            req.getSession().setAttribute("user",user);
            resp.sendRedirect( "index.jsp");
        }else{
            req.setAttribute("msg","用户名或密码错误");
            req.getRequestDispatcher("login.jsp").forward(req,resp);
        }
    }
}
